using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using RabbitMQ.Client;

namespace BuildingBlocks.Infrastructure.EventBus.RabbitMQ;

public static class EventBusRabbitMQDI
{
    public static IServiceCollection AddEventBus(this IServiceCollection services, IConfiguration configuration)
    {
        services.Configure<RabbitMQSettings>(configuration.GetSection("RabbitMQ"));
        services.AddSingleton<IRabbitMQPersistentConnection>(sp =>
        {
            var logger = sp.GetRequiredService<ILogger<DefaultRabbitMQPersistentConnection>>();
           
            var settings = sp.GetRequiredService<IOptions<RabbitMQSettings>>().Value;

            var factory = new ConnectionFactory()
            {
                HostName = settings.HostName,
                UserName = settings.UserName,
                Password = settings.Password,
                Port = settings.Port,
                VirtualHost = settings.VirtualHost,
                 DispatchConsumersAsync = true
            };
            return new DefaultRabbitMQPersistentConnection(factory, logger);
        });

        services.AddSingleton<IEventBus, RabbitMQEventBus>();
        return services;
    }
}